package com.pimee.service.admin.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.pimee.common.util.StringUtils;
import com.pimee.mapper.ext.ExtSysUserMapper;
import com.pimee.model.SysUserOnline;
import com.pimee.service.BaseService;
import com.pimee.service.admin.ISysUserOnlineService;

import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;

@Slf4j
@Service
public class SysUserOnlineService extends BaseService<SysUserOnline> implements ISysUserOnlineService {

	@Autowired
	private ExtSysUserMapper extSysUserMapper;
	
	@Override
	public PageInfo<Map<String, Object>> pageList(Map<String, Object> params) {
		log.info("===> 在线用户列表分页查询...");
		startPage(params);// 设置分页
		List<Map<String, Object>> list = extSysUserMapper.pageOnlineList(params);
		return new PageInfo<>(list);
	}
	
	@Override
	public List<SysUserOnline> selectOnlineByExpired(Date expiredDate) {
		Example example = new Example(SysUserOnline.class);
		example.createCriteria().andLessThanOrEqualTo("lastAccessTime", expiredDate);
		return this.selectByExample(example);
	}

	@Override
	public void deleteOnlineBySessionId(String sessionId) {
		Example example = new Example(SysUserOnline.class);
		example.createCriteria().andEqualTo("sessionId", sessionId);
		this.deleteBy(example);
	}

	@Override
	public SysUserOnline selectOnlineBySessionId(String sessionId) {
		Example example = new Example(SysUserOnline.class);
		example.createCriteria().andEqualTo("sessionId", sessionId);
		example.setOrderByClause(" create_time desc limit 1");
		return this.selectOneByExample(example);
	}

	@Override
	public void batchDeleteOnline(List<String> needOfflineIdList) {
		for (String sessionId : needOfflineIdList) {
			SysUserOnline userOnline = selectOnlineBySessionId(sessionId);
			if (StringUtils.isNotNull(userOnline)) {
				this.deleteOnlineBySessionId(sessionId);
			}
		}
	}
	
	@Override
	public void saveOnline(SysUserOnline param) {
		extSysUserMapper.saveOnline(param);
	}

}
